<?php
defined('BY_JYA') or exit('Access Denied');
if($_SESSION['uniacid'] ==2){
	return false;
}
if($do=='getbuyed'){
	$params=array('uniacid'=>$_SESSION['uniacid'],'type'=>1,'status'=>1);
	$installed=$_RQ['plugins'];
	if($_RQ['installed']){
		//兼容新的提交机制
		$installed=explode(';',$_RQ['installed']);
	}
	$plugins=pdo_getall('core_trade',$params,array('pid'),'pid');
	if(!empty($plugins)){
		$plugins=array_keys($plugins);
		if($installed){
			$plugins=array_diff($plugins,$installed);
		}
		if($plugins){
			$params=array('status'=>1,'show'=>1,'id'=>$plugins);
			if(!empty($_RQ['title'])){
				$params['title like']='%'.trim($_RQ['title']).'%';
			}
			$plugins=pdo_getall('core_plugin',$params,array('id','name','title','version','ability','type','image'));
			foreach($plugins as &$row){
				$row['image']=$row['image'] ? tomedia($row['image']) : '../core/resource/images/nopic.jpg';
			}
		}else{
			$plugins=array();
		}
	}
	eci($plugins);
}
if($do=='upendtime'){
	$params=array('uniacid'=>$_SESSION['uniacid'],'type'=>1,'status'=>1);
	if($_RQ['installed']){
		//兼容新的提交机制
		$installed=explode(';',$_RQ['installed']);
		$params['pid']=$installed;
	}
	$plugins=pdo_getall('core_trade',$params,array('pid','endtime'),'pid');
	if(!empty($plugins)){
	}else{
		$plugins=array();
	}
	eci($plugins);
}
if($do=='getup'){
	$ids=trim($_RQ['cloud_ids']);
	if(!$ids){
		eci('页面参数错误！','error');
	}
	$ids=explode(';',$ids);
	$plugins=pdo_getall('core_plugin',array('id'=>$ids),array('id','release','version','sys_version','v_desc'),'id');
	eci($plugins);
}
if($do=='pre_install'){
	//安装前的依赖检测，这里改为返回依赖的乐高零件
	$id=intval($_RQ['cloud_id']);
	check_buy($id);
	$plugin=pdo_get('core_plugin',array('id'=>$id),array('config','diy_legao'));
	if(!$plugin['diy_legao']){
		eci(false);
	}
	$diy_legao=json_decode($plugin['diy_legao'],true);
	foreach($diy_legao as $k=>$legao){
		$legao['id']=pdo_getcolumn('core_plugin',array('name'=>$legao['name']),'id');
		$yes=pdo_getcolumn('core_trade',array('uniacid'=>CLOUDKEY,'type'=>1,'pid'=>$legao['id'],'status'=>1),'id');
		if(!$yes){
			unset($diy_legao[$k]);
		}
	}
	eci($diy_legao);
	$config=cfc('files')->source_read($plugin['config']);
	$config=@unserialize($config);
	$config['bases']=trim($config['bases'],';');
	if($config['bases']){
		$base_plugins=explode(';',$config['bases']);
		eci($base_plugins);
	}else{
		eci(false);
	}
	
}

if($do=='install'){
	$id=intval($_RQ['cloud_id']);
	if(!$id){
		eci('请先选择要安装的插件！','error');
	}
	check_buy($id);
	$plugin=pdo_get('core_plugin',array('id'=>$id),array('id','name','basic','title','description','type','diypage','actionlinks','istakeover','style','intype','version','release','ability','config','md5','image','hdp','welcomehdps','zipfile','is_legao','diy_legao','msgtpl'));
	$plugin['endtime']=pdo_getcolumn('core_trade',array('uniacid'=>CLOUDKEY,'type'=>1,'pid'=>$id,'status'=>1),'endtime');
	if(!$plugin['zipfile']){
		eci('插件参数错误，缺少安装文件！','error');
	}
	$zipname=PLUGIN_ZIP.$plugin['zipfile'].'.zip';
	$fsize=filesize($zipname);
	$size=204800;
	$plugin['parts']=ceil($fsize/$size);
	unset($plugin['zipfile']);
	if($_RQ['new']){
		$parts=intval($plugin['parts']);
		$download=array(
			'uniacid'=>$_SESSION['uniacid'],
			'type'=>2,
			'size'=>$size,
			'parts'=>$parts,
			'createtime'=>TIMESTAMP,
			'zipfile'=>str_replace(ROOT_AT,'',$zipname),
			'remark'=>"安装插件【{$plugin['title']}（{$plugin['name']}）】",
		);
		pdo_insert('core_cloud_download',$download);
		$id=pdo_insertid();
		$plugin['files']=array('id'=>$id,'parts'=>$parts);
	}
	if($plugin['image']){
		$plugin['image']=tomedia($plugin['image']);
	}
	if($plugin['hdp']){
		$plugin['hdp']=json_decode($plugin['hdp'],true);
		foreach($plugin['hdp'] as &$hv){
			$hv=tomedia($hv);
		}
	}
	if($plugin['welcomehdps']){
		$plugin['welcomehdps']=json_decode($plugin['welcomehdps'],true);
		foreach($plugin['welcomehdps'] as &$whv){
			$whv['picurl']=tomedia($whv['picurl']);
		}
	}
	if(!$plugin['config']){
		eci('插件缺少配置参数！','error');
	}
	$config=cfc('files')->source_read($plugin['config']);
	//eci($config,'error');
	$config=@unserialize($config);
	if(!$config){
		eci('插件配置参数错误！','error');
	}
	
	unset($plugin['config']);
	$plugin=array_merge($plugin,$config);
	//数据库代码需要进行表前缀替换
	$sqls='';
	//如果安装sql是数组则遍历整理，否则直接整理
	if($plugin['install']){
		if(is_array($plugin['install'])){
			foreach($plugin['install'] as $name=>$row){
				$sqls.=str_replace('CREATE TABLE `'.$name.'`','CREATE TABLE IF NOT EXISTS `'.WEB_TABLE_PRE.$name.'`',$row).';';
			}
		}else{
			$sqls=$plugin['install'];
			$sqls=base64_decode($sqls);
			$sqls=preg_replace('/`ims_([\w_]+)`/','`'.WEB_TABLE_PRE.'$1`',$sqls);
		}
	}
	$plugin['install']=$sqls;
	eci($plugin);
}
if($do=='installdata'){
	//获取插件安装文件
	$plugin_id=intval($_RQ['cloud_id']);
	if(!$plugin_id){
		eci('请先选择插件！','error');
	}
	check_buy($plugin_id);
	$plugin=pdo_get('core_plugin',array('id'=>$plugin_id),array('title','name','zipfile'));
	if(!$plugin['zipfile']){
		eci('插件参数错误，缺少安装文件！','error');
	}
	$zipname=PLUGIN_ZIP.$plugin['zipfile'].'.zip';
	$fsize=filesize($zipname);
	$size=204800;
	$parts=intval(ceil($fsize/$size));
	$download=array(
		'uniacid'=>$_SESSION['uniacid'],
		'type'=>2,
		'size'=>$size,
		'parts'=>$parts,
		'createtime'=>TIMESTAMP,
		'zipfile'=>str_replace(ROOT_AT,'',$zipname),
		'remark'=>"安装插件【{$plugin['title']}（{$plugin['name']}）】",
	);
	pdo_insert('core_cloud_download',$download);
	$id=pdo_insertid();
	$res=array('id'=>$id,'parts'=>$parts);
	eci($res);
}
if($do=='build'){
	$id=intval($_RQ['cloud_id']);
	if(!$id){
		eci('请先选择要更新的应用！','error');
	}
	check_buy($id);	
	$return=array();
	//获取插件信息
	$plugin=pdo_get('core_plugin',array('id'=>$id),array('type','name','basic','diypage','actionlinks','istakeover','style','intype','title','version','ability','config','release','image','is_legao','diy_legao','msgtpl'));
	$plugin['endtime']=pdo_getcolumn('core_trade',array('uniacid'=>CLOUDKEY,'type'=>1,'pid'=>$id,'status'=>1),'endtime');
	//整理文件
	$return['files']=array();
	$module_files=cfc('files')->file_tree(PLUGIN_FILE.$plugin['name'],array('/manifest.xml'));
	foreach($module_files as $file){
		$md5=md5_file(PLUGIN_FILE.$plugin['name'].$file);
		$return['files'][]=array('path'=>$file,'checksum'=>$md5);
	}
	if($_RQ['only_file']){
		//只需文件数据，直接返回
		eci($return);
	}
	$config=cfc('files')->source_read($plugin['config']);
	if(!$config){
		eci('更新失败，获取插件配置异常，请联系市场客服！','error');
	}
	$config=@unserialize($config);
	unset($plugin['config']);
	$plugin=array_merge($plugin,$config);
	if($plugin['image']){
		$plugin['image']=tomedia($plugin['image']);
	}
	//生成更新sql
	$oldsqls=$_RQ['sqls'];
	$new_sqls=$config['install'];
	$upsqls='';
	if($new_sqls && is_array($new_sqls)){
		foreach($new_sqls as $name=>$sql){
			$upsql='';
			
			if($oldsqls[$name]){
				$cloud_sql=update($sql);
				$local_sql=update($oldsqls[$name]);
				foreach($cloud_sql['fields'] as $key1=>$field){
					if($local_sql['fields'][$key1]){
						if($local_sql['fields'][$key1]!=$field){
							//$field=str_replace("'","\'",$field);
							$upsql.='ALTER TABLE `'.WEB_TABLE_PRE.$name.'` CHANGE `'.$key1.'` '.$field.';';
						}
					}else{
						//$field=str_replace("'","\'",$field);
						$upsql.='ALTER TABLE `'.WEB_TABLE_PRE.$name.'` ADD '.$field.';';
						
					}
				}
				foreach($cloud_sql['indexs'] as $key2=>$index){
					if($local_sql['indexs'][$key2]){
						if($local_sql['indexs'][$key2]!=$index){
							//$index=str_replace("'","\'",$index);取消增加反斜杠，反斜杠增加反而导致出错，因为这个sql是直接拿来执行的
							$upsql.='ALTER TABLE `'.WEB_TABLE_PRE.$name.'` DROP INDEX `'.$key2.'`, ADD '.$index.';';
							
						}
					}else{
						//$index=str_replace("'","\'",$index);
						$upsql.='ALTER TABLE `'.WEB_TABLE_PRE.$name.'` ADD '.$index.';';
						
					}
				}
			}else{
				//$sql=str_replace("'","\'",$sql);取消该代码说明，该sql是直接送去执行的，无需拼接入文件，因此无需进行转义
				$sql=str_replace('CREATE TABLE `'.$name.'`','CREATE TABLE IF NOT EXISTS `'.WEB_TABLE_PRE.$name.'`',$sql);
				$upsql.=$sql.';';
				
			}
			if($upsql){
				$upsqls.=$upsql;
			}
		}
	}
	
	$return['upsqls']=$upsqls;
	//检查更新代码
	$updata=pdo_getall('core_plugin_version',array('release >'=>$_RQ['release']),array('updata'),'updata');
	$updata=array_keys($updata);
	$return['updata']=$updata;
	//整理版本数据
	unset($plugin['install']);
	$return['plugin']=$plugin;
	eci($return);
}
if($do=='getmodule'){
	$id=intval($_RQ['cloud_id']);
	if(!$id){
		eci('请先选择要更新的应用！1','error');
	}
	check_buy($id);
	$return=array();
	//获取插件信息
	$plugin=pdo_get('core_plugin',array('id'=>$id),array('name','title'));
	if(!$plugin['name']){
		eci('应用不存在！','error');
	}
	$files=$_RQ['files'];
	$zip = new ZipArchive();
	$zipname=cfc('files')->get_source_name('data','data');
    $zip->open(ROOT_AT.$zipname, ZipArchive::CREATE);
	foreach($files as $file){
		if(!empty($file)){
			$fname = PLUGIN_FILE.$plugin['name']. $file;
			if(is_file($fname)){
				$zip->addFile($fname,$file);
			}
			
		}
	}
	$zip->close();
	if($_RQ['new']==1){
		//采用新方法下载更新数据
		$filesize=filesize(ROOT_AT.$zipname);
		$size=204800;
		$parts=ceil($filesize/$size);
		$parts=intval($parts);
		$download=array(
			'uniacid'=>$_SESSION['uniacid'],
			'type'=>4,
			'size'=>$size,
			'parts'=>$parts,
			'createtime'=>TIMESTAMP,
			'zipfile'=>$zipname,
			'remark'=>"更新插件【{$plugin['title']}（{$plugin['name']}）】",
		);
		pdo_insert('core_cloud_download',$download);
		$id=pdo_insertid();
		$return=array('id'=>$id,'parts'=>$parts);
		eci($return);
	}
	if(is_file(ROOT_AT.$zipname)){
		$return=file_get_contents(ROOT_AT.$zipname);
	}else{
		$return='';
	}
	eci($return);
}
